// user接口
const express = require('express')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const {
    secret
} = require('../config/key')
const userRouter = express.Router()
const User = require('../model/userModel') //引入数据模型
const verify_token = require('../middleware/verifyToken')
const verify_usr_role = require('../middleware/verifyUsrRole')
const {
    roleList
} = require('../utils/index')

// 获取用户列表
userRouter.get('/', verify_token, async (req, res) => {
    const allUser = await User.find()
    res.json({
        status: 1,
        msg: '查询成功',
        data: allUser
    })
})

// 注册账号
userRouter.post('/register', async (req, res) => {
    const isExist = await User.findOne({
        name: req.body.name
    })
    if (isExist) {
        return res.json({
            status: 0,
            msg: '该用户已存在'
        })
    }

    const newUser = await new User(req.body).save()
    // 返回用户
    res.json({
        status: 1,
        msg: '注册成功',
        data: newUser
    })
})

// 登录
userRouter.post('/login', async (req, res) => {
    const exist = await User.findOne({
        name: req.body.name
    })
    let result = JSON.stringify(exist)
    result = JSON.parse(result)
    result.ruleArray = roleList(exist.identity)
    // 判断用户是否存在
    if (!result) {
        return res.json({
            status: 2,
            msg: '用户不存在'
        })
    }
    // 用户存在，判断用户密码是否正确
    let isPass = bcrypt.compareSync(req.body.pass, result.pass)

    if (!isPass) {
        return res.json({
            status: 3,
            msg: '请输入正确的口令码/账号/密码'
        })
    }
    const {
        _id,
        name,
        identity
    } = result
    const token = jwt.sign({
        _id,
        name
    }, secret, {
        expiresIn: '5h'
    })
    res.json({
        status: 1,
        msg: '登录成功',
        token,
        userInfo: result
    })
})

// 删除用户，只有超管有权限
userRouter.delete('/deleteUsr/:id', verify_usr_role, (req, res) => {

})


// 验证token是否过期
userRouter.get('/verify', verify_token, (req, res) => {})


module.exports = userRouter